package com.toocms.tab.widget.pictureadder;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableList;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.toocms.tab.R;
import com.toocms.tab.binding.command.BindingCommand;
import com.toocms.tab.imageload.engine.CompressEngine;
import com.toocms.tab.imageload.engine.GlideEngine;
import com.toocms.tab.imageload.engine.SandboxEngine;
import com.toocms.tab.imageload.psui.PsUI;

import java.util.ArrayList;
import java.util.List;

/**
 * 图片/视频添加控件
 * Author：Zero
 * Date：2020/1/21 14:38
 *
 * @version v5.0
 */
public class PictureAdderView extends RecyclerView implements PictureAdderAdapter.OnAddPictureClickListener, OnItemClickListener {

    private PictureAdderAdapter adapter;

    public BindingCommand<List<LocalMedia>> onResultCommand;

    private ObservableList<LocalMedia> selectList = new ObservableArrayList<>();
    private int numColumns;
    private int spacing;
    private int chooseMode;
    private int maxSelectNum;
    private int maxVideoSelectNum;
    private int videoMaxSecond;
    private int recordVideoSecond;

    public PictureAdderView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        parseStyle(context, attrs);
        init(context);
    }

    private void parseStyle(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.PictureAdderView);
        spacing = (int) typedArray.getDimension(R.styleable.PictureAdderView_spacing, SizeUtils.dp2px(10));
        numColumns = typedArray.getInteger(R.styleable.PictureAdderView_numColumns, 4);
        chooseMode = typedArray.getInt(R.styleable.PictureAdderView_chooseMode, 1);
        maxSelectNum = typedArray.getInteger(R.styleable.PictureAdderView_maxSelectNum, 9);
        maxVideoSelectNum = typedArray.getInteger(R.styleable.PictureAdderView_maxVideoSelectNum, 1);
        videoMaxSecond = typedArray.getInteger(R.styleable.PictureAdderView_videoMaxSecond, 120);
        recordVideoSecond = typedArray.getInteger(R.styleable.PictureAdderView_recordVideoSecond, 120);
    }

    private void init(@NonNull Context context) {
        setOverScrollMode(OVER_SCROLL_NEVER);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(context, numColumns, GridLayoutManager.VERTICAL, false);
        setLayoutManager(manager);
        addItemDecoration(new GridSpacingItemDecoration(numColumns, spacing, false));
        adapter = new PictureAdderAdapter(context, this);
        adapter.setOnItemClickListener(this);
        adapter.setSelectMax(maxSelectNum);
        setAdapter(adapter);
    }

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    public void onAddPictureClick() {
        PictureSelector.create(ActivityUtils.getTopActivity())
                .openGallery(chooseMode)    // 扫描文件类型
                .setSelectorUIStyle(PsUI.createPsUI()) // 相册启动退出动画
                .setImageEngine(GlideEngine.createGlideEngine())   // 图片加载引擎
                .setCompressEngine(CompressEngine.createCompressEngine())   // 压缩加载引擎
                .setSandboxFileEngine(SandboxEngine.createSandboxEngine())
                .isWithSelectVideoImage(true) // 图片和视频是否可以同选,只在ofAll模式下有效
                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)  // 相册Activity方向
                .isOriginalControl(false)  // 不显示原图控制按钮
                .setMaxSelectNum(maxSelectNum) // 最大选择数量
                .setSelectionMode(SelectModeConfig.MULTIPLE)    // 多选
                .setSelectedData(selectList) //  传入已选数据
                .setFilterVideoMaxSecond(videoMaxSecond) // 显示多少秒以内的视频or音频
                .setRecordVideoMaxSecond(recordVideoSecond)  //  视频录制秒数
                .forResult(new OnResultCallbackListener<>() {

                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        selectList.clear();
                        selectList.addAll(result);
                        adapter.setList(selectList);
                        adapter.notifyDataSetChanged();
                        if (onResultCommand != null) onResultCommand.execute(result);
                    }

                    @Override
                    public void onCancel() {

                    }
                });   // 回调
    }

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    public void onItemClick(int position, View v) {
        if (selectList.size() > 0) {
            ArrayList<LocalMedia> list = new ArrayList<>(selectList);
            PictureSelector.create(ActivityUtils.getTopActivity())
                    .openPreview()
                    .setImageEngine(GlideEngine.createGlideEngine())
                    .setExternalPreviewEventListener(new OnExternalPreviewEventListener() {
                        @Override
                        public void onPreviewDelete(int position) {
                            adapter.remove(position);
                            adapter.notifyItemRemoved(position);
                        }

                        @Override
                        public boolean onLongPressDownload(Context context, LocalMedia media) {
                            return false;
                        }
                    }).startActivityPreview(position, true, list);
        }
    }

    /**
     * 设置上传图片回调
     *
     * @param onResultCommand
     */
    public void setOnResultCommand(BindingCommand<List<LocalMedia>> onResultCommand) {
        this.onResultCommand = onResultCommand;
        adapter.setOnResultCommand(onResultCommand);
    }

    /**
     * 获取已选择的媒体文件
     *
     * @return
     */
    @Deprecated
    public ObservableList<LocalMedia> getSelectList() {
        return selectList;
    }
}
